//
//  CarrierAgreementView.swift
//  Pods
//
//  Created by Bingo on 2025/8/26.
//

// 链接类型枚举
enum AgreementLinkType {
    case userAgreement
    case privacyPolicy
    case carrierAgreement
}

// 弹窗回调类型
typealias AgreementAction = () -> Void
typealias AgreementLinkAction = (AgreementLinkType) -> Void
typealias AgreementCompletion = (Bool) -> Void

class CarrierAgreementView: UIView ,UITextViewDelegate{
    
    // MARK: - UI Components
    private let containerView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.layer.cornerRadius = 12
        view.layer.masksToBounds = true
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()
    
    private let titleLabel: UILabel = {
        let label = UILabel()
        label.text = "协议确认"
        label.font = UIFont.boldSystemFont(ofSize: 18)
        label.textAlignment = .center
        label.textColor = .darkText
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()
    
    private let messageTextView: UITextView = {
        let textView = UITextView()
        textView.isEditable = false
        textView.isScrollEnabled = true
        textView.font = UIFont.systemFont(ofSize: 14)
        textView.textColor = .darkGray
        textView.textContainerInset = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 8)
        textView.translatesAutoresizingMaskIntoConstraints = false
        return textView
    }()
    
    private let cancelButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("取消", for: .normal)
        button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
        button.setTitleColor(.darkGray, for: .normal)
        button.backgroundColor = UIColor(white: 0.95, alpha: 1.0)
        button.layer.cornerRadius = 6
        button.translatesAutoresizingMaskIntoConstraints = false
        return button
    }()
    
    private let confirmButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("同意并继续", for: .normal)
        button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
        button.setTitleColor(.white, for: .normal)
        button.backgroundColor = UIColor.init(red: 165/255.0, green: 0, blue: 0, alpha: 1.0)
        button.layer.cornerRadius = 6
        button.translatesAutoresizingMaskIntoConstraints = false
        return button
    }()
    
    private let buttonStackView: UIStackView = {
        let stackView = UIStackView()
        stackView.axis = .horizontal
        stackView.distribution = .fillEqually
        stackView.spacing = 12
        stackView.translatesAutoresizingMaskIntoConstraints = false
        return stackView
    }()
    
    // MARK: - Block Callbacks
    private var onConfirm: AgreementAction?
    private var onCancel: AgreementAction?
    private var onLinkTap: AgreementLinkAction?
    
    // MARK: - Initialization
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        setupActions()
        setupAttributedText()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupUI()
        setupActions()
        setupAttributedText()
    }
    
    // MARK: - Configuration
    func configure(onConfirm: AgreementAction? = nil,
                   onCancel: AgreementAction? = nil,
                   onLinkTap: AgreementLinkAction? = nil) {
        self.onConfirm = onConfirm
        self.onCancel = onCancel
        self.onLinkTap = onLinkTap
    }
    
    // MARK: - UI Setup
    private func setupUI() {
        backgroundColor = UIColor.black.withAlphaComponent(0.5)
        
        // 添加容器视图
        addSubview(containerView)
        
        // 添加标题
        containerView.addSubview(titleLabel)
        
        // 添加消息文本
        containerView.addSubview(messageTextView)
        
        // 添加按钮堆栈
        buttonStackView.addArrangedSubview(cancelButton)
        buttonStackView.addArrangedSubview(confirmButton)
        containerView.addSubview(buttonStackView)
        
        // 设置约束
        NSLayoutConstraint.activate([
            // 容器视图约束
            containerView.centerXAnchor.constraint(equalTo: centerXAnchor),
            containerView.centerYAnchor.constraint(equalTo: centerYAnchor),
            containerView.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 0.8),
            containerView.heightAnchor.constraint(lessThanOrEqualTo: heightAnchor, multiplier: 0.6),
            
            // 标题约束
            titleLabel.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 20),
            titleLabel.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 16),
            titleLabel.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -16),
            
            // 消息文本约束
            messageTextView.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 16),
            messageTextView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 8),
            messageTextView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -8),
            messageTextView.heightAnchor.constraint(equalToConstant: 80),
            messageTextView.centerXAnchor.constraint(equalTo: containerView.centerXAnchor),
            messageTextView.centerYAnchor.constraint(equalTo: containerView.centerYAnchor),
            
            // 按钮堆栈约束
            buttonStackView.topAnchor.constraint(equalTo: messageTextView.bottomAnchor, constant: 10),
            buttonStackView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 16),
            buttonStackView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -16),
            buttonStackView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: -20),
            buttonStackView.heightAnchor.constraint(equalToConstant: 44)
        ])
    }
    
    // MARK: - Actions Setup
    private func setupActions() {
        cancelButton.addTarget(self, action: #selector(cancelTapped), for: .touchUpInside)
        confirmButton.addTarget(self, action: #selector(confirmTapped), for: .touchUpInside)
        
        // 添加点击背景关闭的手势
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(backgroundTapped))
        tapGesture.delegate = self
        addGestureRecognizer(tapGesture)
    }
    
    // MARK: - Text Setup
    private func setupAttributedText() {
        let agreementText = "使用前请您仔细阅读并同意以下协议《用户使用协议》、《隐私政策》和《运营商认证服务协议》。"
        
        // 创建可点击的链接文本
        let attributedString = NSMutableAttributedString(string: agreementText)
        
        attributedString.addAttribute(.font, value: UIFont.systemFont(ofSize: 15), range: NSRange(location: 0, length: agreementText.count))
        
        // 设置段落样式
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = 2 // 行间距
        //                paragraphStyle.minimumLineHeight = 30 // 最小行高
        //                paragraphStyle.maximumLineHeight = 30 // 最大行高
        
        // 设置文本属性
        let attributes: [NSAttributedString.Key: Any] = [
            .paragraphStyle: paragraphStyle
        ]
        
        attributedString.addAttributes(attributes, range: NSRange(location: 0, length: agreementText.count))
        
        // 添加链接
        let userAgreementRange = (agreementText as NSString).range(of: "《用户使用协议》")
        let privacyPolicyRange = (agreementText as NSString).range(of: "《隐私政策》")
        let carrierAgreementRange = (agreementText as NSString).range(of: "《运营商认证服务协议》")
        
        attributedString.addAttribute(.link, value: "userAgreement://", range: userAgreementRange)
        attributedString.addAttribute(.link, value: "privacyPolicy://", range: privacyPolicyRange)
        attributedString.addAttribute(.link, value: "carrierAgreement://", range: carrierAgreementRange)
        
        // 设置链接颜色
        attributedString.addAttribute(.foregroundColor, value: UIColor.init(red: 165/255.0, green: 0, blue: 0, alpha: 1.0), range: userAgreementRange)
        attributedString.addAttribute(.foregroundColor, value: UIColor.init(red: 165/255.0, green: 0, blue: 0, alpha: 1.0), range: carrierAgreementRange)
        
        messageTextView.attributedText = attributedString
        messageTextView.linkTextAttributes = [
            .foregroundColor: UIColor.init(red: 165/255.0, green: 0, blue: 0, alpha: 1.0),
            .underlineStyle: NSUnderlineStyle.byWord.rawValue
        ]
        messageTextView.delegate = self
        
    }
    
    
    @objc private func cancelTapped() {
        hide()
        onCancel?()
    }
    
    @objc private func confirmTapped() {
        hide()
        onConfirm?()
    }
    
    @objc private func backgroundTapped() {
        hide()
        onCancel?()
    }
    
    // MARK: - UITextViewDelegate
    func textView(_ textView: UITextView, shouldInteractWith url: URL, in characterRange: NSRange) -> Bool {
        
        if url.scheme == "userAgreement" {
            onLinkTap?(.userAgreement)
        } else if url.scheme == "privacyPolicy" {
            onLinkTap?(.privacyPolicy)
        } else if url.scheme == "carrierAgreement" {
            onLinkTap?(.carrierAgreement)
        }
        
        return false
    }
    
    
    // MARK: - Show/Hide Methods
    func show(in view: UIView) {
        // 设置初始状态
        alpha = 0
        transform = CGAffineTransform(scaleX: 1.1, y: 1.1)
        
        // 添加到父视图
        view.addSubview(self)
        
        // 设置约束
        translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            topAnchor.constraint(equalTo: view.topAnchor),
            leadingAnchor.constraint(equalTo: view.leadingAnchor),
            trailingAnchor.constraint(equalTo: view.trailingAnchor),
            bottomAnchor.constraint(equalTo: view.bottomAnchor)
        ])
        
        // 动画显示
        UIView.animate(withDuration: 0.3) {
            self.alpha = 1
            self.transform = CGAffineTransform.identity
        }
    }
    
    func hide() {
        UIView.animate(withDuration: 0.1, animations: {
            self.alpha = 0
            self.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
        }) { _ in
            self.removeFromSuperview()
        }
    }
    
    // MARK: - Static Convenience Method
    static func show(in view: UIView,
                     onConfirm: AgreementAction? = nil,
                     onCancel: AgreementAction? = nil,
                     onLinkTap: AgreementLinkAction? = nil) {
        let agreementView = CarrierAgreementView()
        agreementView.configure(onConfirm: onConfirm, onCancel: onCancel, onLinkTap: onLinkTap)
        agreementView.show(in: view)
    }
}

// MARK: - UIGestureRecognizerDelegate
extension CarrierAgreementView: UIGestureRecognizerDelegate {
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        // 只有当点击的是背景时才处理手势
        return touch.view == self
    }
}
